package br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.home.info;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.services.UserService;
import br.edu.ufcg.lsd.wbis.ui.client.ui.FormManager;
import br.edu.ufcg.lsd.wbis.ui.client.ui.SubmitFormButtonListener;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.Updatable;
import br.edu.ufcg.lsd.wbis.ui.client.ui.management.InfoManager;

import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Window;

public class UpdatePasswordButtonListener extends SubmitFormButtonListener<UserInfo> {

	private final InfoManager<UserInfo> infoManager;
	private final Updatable<UserInfo> parentPortlet;
	private final InfoManager<UserInfo> loggedInfoManager;

	public UpdatePasswordButtonListener(Window enclosingWindow, FormManager<UserInfo> formManager, Updatable<UserInfo> parentPortlet,
			InfoManager<UserInfo> infoManager, InfoManager<UserInfo> loggedInfoManager) {
		super(enclosingWindow, formManager);
		this.infoManager = infoManager;
		this.parentPortlet = parentPortlet;
		this.loggedInfoManager = loggedInfoManager;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onClick(Button button, EventObject e) {
		final UserInfo parsedInfo = this.getParsedInfo();
		if (!parsedInfo.isPasswordValid()) {
			MessageBox.alert("Error", "Password must not be empty!");
			return;
		}
		if (!parsedInfo.isPasswordRetyped()) {
			MessageBox.alert("Error", "The retyped password does not match!");
			return;
		}
		final UserInfo currentInfo = infoManager.getInfo();
		MessageBox.confirm("Confirm", "Are you sure you want to update this user's password? ", new MessageBox.ConfirmCallback() {
			public void execute(String btnID) {
				if (btnID.equals("yes")) {
					parsedInfo.setLogin(currentInfo.getLogin());
					final UserInfo loggedInfo = loggedInfoManager.getInfo();
					UserService.Util.getInstance().changePassword(loggedInfo.getLogin(), loggedInfo.getPassword(), parsedInfo,
							new UpdateInfoCallback(parentPortlet));
					getEnclosingWindow().destroy();
				}
			}
		});
	}

}
